package com.ac.api.qms_nonconformance.controller;

import com.ac.api.qms_meterial_standard.entity.QmsMeterialStandard;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import com.base.annotation.SysLog;
import org.springframework.web.bind.annotation.RestController;
import com.base.helper.BaseController;
import com.base.helper.Result;
import com.ac.api.qms_nonconformance.entity.QmsNonconformance;
import com.ac.api.qms_nonconformance.service.QmsNonconformanceService;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import javax.validation.Valid;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ry
 * @since 2025-06-16
 */
@Api(tags = "QmsNonconformance")
@RestController
@RequestMapping("/qmsNonconformance")
public class QmsNonconformanceController extends BaseController {

        private static final Logger       LOG = LoggerFactory.getLogger(QmsNonconformanceController.class);
        @Autowired
        private              QmsNonconformanceService entityService;

        @SysLog(action = "findByPage", value = "分页查询不合格品")
        @ApiOperation(value = "分页查询不合格品", notes = "分页查询不合格品")
        @GetMapping(value = "/findByPage")
        @ApiImplicitParams({@ApiImplicitParam(name = "size", value = "分页大小", paramType = "query"),
                @ApiImplicitParam(name = "current", value = "当前页面：从1开始", paramType = "query")})
        public Result<IPage<QmsNonconformance>> findByPage(final QmsNonconformance example, final Page page) {
            IPage<QmsNonconformance>        records    = entityService.page(example,page);
            return new Result(true, records);
        }

        @SysLog(action = "delete", value = "删除不合格品")
        @ApiOperation(value = "删除不合格品")
        @DeleteMapping(value = "/delete")
        @ApiImplicitParam(name = "id", value = "不合格品ID", required = true)
        public Result delete(@RequestParam Integer id) {
            try {
                entityService.removeById(id);
                return new Result(true, "成功删除不合格品", null);
            } catch (DataIntegrityViolationException e) {
                LOG.error("删除不合格品失败", e);
                return new Result(false, "删除不合格品失败", "该不合格品不能删除，存在其他关联数据");
            } catch (Exception e) {
                LOG.error("删除不合格品失败", e);
                return new Result(false, "删除不合格品失败", e.getMessage());
            }
        }

        @SysLog(action = "one", value = "查询单个不合格品")
        @ApiOperation(value = "查询单个不合格品")
        @GetMapping(value = "/check")
        @ApiImplicitParam(name = "id", value = "不合格品ID", required = true)
        public Result one(@RequestParam Integer id) {
            try {
                QmsNonconformance entity = entityService.getById(id);
                return new Result(true, entity);
            } catch (Exception e) {
                LOG.error("查询单个不合格品失败", e);
                return new Result(false, new QmsNonconformance());
            }
        }

    @SysLog(action = "search", value = "搜索不合格品")
    @ApiOperation(value = "搜索不合格品")
    @GetMapping(value = "/search")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "recordId", value = "关联检验记录ID", required = false, dataType = "int"),
            @ApiImplicitParam(name = "handleType", value = "处理方式", required = false),
            @ApiImplicitParam(name = "pageNum", value = "页码", defaultValue = "1", dataType = "int"),
            @ApiImplicitParam(name = "pageSize", value = "每页数量", defaultValue = "10", dataType = "int")
    })
    public Result search(
            @RequestParam(required = false) Integer recordId,
            @RequestParam(required = false) String handleType,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        try {
            Page<QmsNonconformance> page = new Page<>(pageNum, pageSize);
            QueryWrapper<QmsNonconformance> queryWrapper = new QueryWrapper<>();

            // 按recordId精确查询（整型）
            if (recordId != null) {
                queryWrapper.eq("record_id", recordId); // 使用eq精确匹配
            }

            // 按handleType模糊查询（字符串）
            if (StringUtils.isNotBlank(handleType)) {
                queryWrapper.like("handle_type", handleType.trim()); // 使用like模糊匹配
            }

            IPage<QmsNonconformance> resultPage = entityService.page(page, queryWrapper);

            // 检查是否有结果
            if (resultPage.getRecords().isEmpty()) {
                return new Result(true, "无匹配结果");
            }

            return new Result(true, resultPage);
        } catch (Exception e) {
            LOG.error("搜索不合格品失败", e);
            return new Result(false, "查询失败，请稍后重试");
        }
    }

        @SysLog(action = "add", value = "添加不合格品")
        @ApiOperation(value = "添加不合格品")
        @PostMapping(value = "/add")
        public Result add(@Valid @RequestBody final QmsNonconformance entity, final BindingResult result) {
            try {
                if (result.hasErrors()) {
                    Map<String, String> map      = this.getErrors(result);
                    String              errorMsg = map.entrySet().iterator().next().getValue();
                    return new Result(false, "保存不合格品失败", errorMsg, map);
                } else {
                    entityService.save(entity);
                    return new Result(true, "成功保存不合格品", null);
                }
            } catch (Exception e) {
                LOG.error("添加不合格品失败", e);
                return new Result(false, "保存不合格品失败", e.getMessage());
            }
        }

        @SysLog(action = "update", value = "修改不合格品")
        @ApiOperation(value = "修改不合格品")
        @PostMapping(value = "/update")
        public Result update(@Valid @RequestBody final QmsNonconformance entity, final BindingResult result) {
            try {
                if (result.hasErrors()) {
                    Map<String, String> map      = this.getErrors(result);
                    String              errorMsg = map.entrySet().iterator().next().getValue();
                    return new Result(false, "修改不合格品失败", errorMsg, map);
                } else {
                    if (null == entity.getId()) {
                         throw new RuntimeException("id不能为空");
                    }
                    entityService.updateById(entity);
                    return new Result(true, "成功修改不合格品", null);
                }
            } catch (Exception e) {
                LOG.error("修改订单失败", e);
                return new Result(false, "修改不合格品失败", e.getMessage());
            }
        }

        @ApiOperation(value = "全部不合格品")
        @GetMapping(value = "/all")
        public Result<List<QmsNonconformance>> all(QmsNonconformance example) {
            List<QmsNonconformance> entitys = entityService.list(example);
            if (null != entitys) {
                return new Result<>(true, entitys);
            }
            return new Result<>(true, Collections.emptyList());
        }

}

